package io.renren.socket;

import com.fasterxml.jackson.annotation.JsonInclude;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class EEs {

    public   static String data;
    public   static List<EquipmentEntity> EquipmentEntitys;
    public static Set<SelectionKey> selectionKeys;
    public static SocketServer server;
    public static Machine machine;

    public static void setEquipmentEntitys(CommContent c,SelectionKey selectionKey){
        for( EquipmentEntity e:EEs.EquipmentEntitys){
            if(e.getId().equals(c.getId())){
                e.setPort(selectionKey.channel().toString());
                return;
            }
        }
        EquipmentEntity e=new EquipmentEntity();
        e.setId(c.getId());
        e.setPort(selectionKey.channel().toString());
        EEs.EquipmentEntitys.add(e);
   }

    public static CommContent setCommContent(String r){
        CommContent c=new CommContent();
            c.setId(r.substring(14, 16));   //设备id
            c.setFunction(r.substring(16, 18));  //功能字
            c.setData(r.substring(18, 30));  //数据域
            c.setCheck(r.substring(30, 34));     //检查字
            c.setEnd(r.substring(34, 40));       //结束
            return c;
        }

    public  static EquipmentEntity getEquipmentEntity(CommContent c){
        for(EquipmentEntity e: EEs.EquipmentEntitys){
         if(e.getId().equals(c.getId())){
             return  e;
         }
        }
        return new EquipmentEntity();
    }

    public  static void sendSocket(CommContent c) throws IOException {

        EquipmentEntity e=EEs.getEquipmentEntity(c);
        EEs.selectionKeys = SocketServer.selector.keys();
        for(SelectionKey selectionKey:EEs.selectionKeys){
            if(selectionKey.channel().toString().equals(e.getPort())){
                EEs.server.send(selectionKey,c);
            }
        }
    }


    public static String getStrByCommContent(CommContent c) {
        //todo  5A5A5A0100000010100100000000005555A5A5A5
        return "5a5a5a01000000"+c.getId()+""+c.getFunction()+c.getData()+c.getCheck()+c.getEnd();
    }

    public static CommContent baojing(CommContent commContent) {
        CommContent cc=new CommContent();
       // CommContent commContent = new CommContent();
        cc.setId(commContent.getId());
        cc.setFunction("11");
        cc.setData(commContent.getData().substring(0,10)+"01");  //光报警打开
        cc.setCheck(commContent.getCheck());
        cc.setEnd(commContent.getEnd());
        //EEs.machine.setAlarmLamp("1");
        return cc;
    }
}
